package org.i1510.common.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import org.i1510.common.bean.PageBean;
import org.i1510.common.dao.ISysAttDao;
import org.i1510.common.po.SysAtt;
import org.i1510.common.service.ISysAttService;
import org.i1510.common.utils.DateUtils;
import org.i1510.common.utils.IDGenerator;
import org.i1510.common.utils.KBProperties;
import org.i1510.common.utils.StringUtils;
import org.i1510.common.utils.UserUtils;
import org.i1510.common.utils.file.FileUtils;
import org.i1510.common.utils.file.ZipUtils;
import org.i1510.common.utils.web.ResultMapper;
import org.i1510.common.utils.web.WebUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

/**
 * @author rambo
 *
 */
@Controller
@RequestMapping(value = "/admin/sysAtt")
public class SysAttController extends BaseController {
	private static final Logger logger = LoggerFactory
			.getLogger(SysAttController.class);
	@Autowired
	private ISysAttService iSysAttService;
	@Autowired
	private ISysAttDao iSysAttDao;

	private ResultMapper mapper;

	/**
	*@Author Rambo
	*@Desc：跨域打包下载（门店版本）
	*@param response
	*@param request
	*@param docIds
	*@param sysAtt
	*@param errors
	*@return TODO
	*@Version  SysAttController.java,v 1.1 2015年9月21日 下午4:02:49 
	*/
	@RequestMapping(value = "/downloadsIf", method = {RequestMethod.GET,RequestMethod.POST})
	@ResponseBody
	public String downloadsIf(HttpServletResponse response,
			HttpServletRequest request, String docIds, 
			@Valid @ModelAttribute("sysAtt") SysAtt sysAtt, BindingResult errors) {
		ResultMapper mapperRtn = ResultMapper.generateFailure();
		if (errors.hasErrors()) {
			mapperRtn = WebUtils.getMapper4Errors(errors);
		} else {
			if (null != docIds) {
				List<String> fileList = new ArrayList<String>();
				JSONArray items = JSONArray.fromObject(docIds);
				String downloadId = "[" + DateUtils.getNowExt1() + "]" + UserUtils.getSessionUserBean(request).getSysUser().getName();
				//总目录
				String rootUser = KBProperties.ZIPTEMP + "/" + downloadId;
				//打包目录
				String rootUserZip = KBProperties.ZIPTEMP + "/" + downloadId+"/zip";
				
				for (int i = 0; i < items.size(); i++) {
					
					JSONObject jsonObject = items.getJSONObject(i);
					String shopName = jsonObject.get("shopName").toString();
					//打包目录
					File dirTempZip = new File(rootUserZip+"/"+shopName);
					if (!dirTempZip.exists()) {
						try {
							dirTempZip.mkdirs();
						} catch (Exception ex) {
							try {
								throw new Exception("不能创建目录 :"
										+ dirTempZip);
							} catch (Exception e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							}
						}
					}
					fileList.add(shopName);

					JSONArray ids = (JSONArray) jsonObject.get("maps");

					// 压缩门店附件
					String zipids = "";
					for (int j = 0; j < ids.size(); j++) {
						JSONObject jo = ids.getJSONObject(j);
						System.out.println("--id=" + jo.get("id"));
						zipids += "," + jo.get("id");
					}

					List docList = Arrays
							.asList(zipids.substring(1).split(","));
					List<SysAtt> sysAttList = iSysAttService.findByIds(docList);
					if (sysAttList.size() > 0) {

							
							File[] files = new File[sysAttList.size()];
							for (int ii = 0; ii < sysAttList.size(); ii++) {
								FileUtils.copy2(sysAttList.get(ii).getAttPath()
										+ "/" + sysAttList.get(ii).getDocId(),
										rootUserZip+"/"+shopName+"/"
												+ sysAttList.get(ii)
														.getDocSubject());
								files[ii] = new File(rootUserZip + "/"+shopName+"/"
										+ sysAttList.get(ii).getDocSubject());
							}
							

					}
					
					

				}
				// 打包所有的
				try {
					ZipUtils.zip(rootUser + "/download.zip", "",
							rootUserZip+"/");
					InputStream is;
				
						is = new FileInputStream(new File(rootUser + "/download.zip"));
						response.setContentType("octet-stream");
						response.setHeader(
								"Content-Disposition",
								"attachment; filename="
										+ downloadId+".zip");
						OutputStream outputStream;
						try {
							outputStream = response.getOutputStream();
							byte[] buffer = new byte[KBProperties.INPUTMAX];
							int jj = -1;
							while ((jj = is.read(buffer)) != -1) {
								outputStream.write(buffer, 0, jj);
							}
							outputStream.flush();
							outputStream.close();
							is.close();
						} catch (IOException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
				} catch (FileNotFoundException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

			}
			
		}
		return null;
	}

	/**
	*@Author Rambo
	*@Desc：跨域上传
	*@param file
	*@param request
	*@param model
	*@param response
	*@param sysAtt
	*@param errors
	*@return TODO
	*@Version  SysAttController.java,v 1.1 2015年9月21日 下午4:03:12 
	*/
	@RequestMapping(value = "/uploadIf", method = RequestMethod.POST)
	@ResponseBody
	public String uploadIf(
			@RequestParam(value = "file", required = false) MultipartFile file,
			HttpServletRequest request, ModelMap model,
			HttpServletResponse response,
			@Valid @ModelAttribute("sysAtt") SysAtt sysAtt, BindingResult errors) {
		mapper = ResultMapper.generateFailure();
		String rtnDocIds="";
		if (!file.isEmpty()) {
			MultipartFile[] files = new MultipartFile[1];
			files[0] = file;
			if (isFileAccess(files)) {
				// 文件类型判断
				String root = KBProperties.FILEUPLOAD;
				File dirTemp = new File(root);
				if (!dirTemp.exists()) {
					try {
						dirTemp.mkdirs();
					} catch (Exception ex) {
						try {
							throw new Exception("不能创建目录 :" + root);
						} catch (Exception e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
					}
				}	
				
				// 文件传输
				String docId = IDGenerator.getGenerateID();	
				SysAtt saved = null;
				try {
					saved = save2FileStream(request, docId, root, file.getInputStream(), file.getContentType(),file.getOriginalFilename()
							.toLowerCase());				
					if (saved != null) {
						rtnDocIds = saved.getDocId();
						mapper = ResultMapper.generateSuccess();
						mapper.appendResult("id", saved.getDocId());
					} else {
						mapper.appendResult("message", "索引保存失败!");
					}
					String fileName = file.getOriginalFilename();
					String suffix = fileName.substring(fileName.lastIndexOf(".")+1);
					//如果上传文件是zip压缩包，解压到zipFiles目录，然后遍历该目录重新以文件流保存至root
					if("zip".equalsIgnoreCase(suffix)){
						ZipUtils.unzip(root+"/"+docId, root+"/zipFiles/"+docId);
						rtnDocIds = saveUnZipFiles(request, root+"/zipFiles/"+docId, root);
						System.out.println(rtnDocIds);
						if (rtnDocIds != null) {
							mapper = ResultMapper.generateSuccess();
							mapper.appendResult("id", rtnDocIds);
						} else {
							mapper.appendResult("message", "索引保存失败!");
						}
					}else if("rar".equalsIgnoreCase(suffix)){
						ZipUtils.unRarFileWithoutAuth(root+"/"+docId, root+"/zipFiles/"+docId);
						rtnDocIds = saveUnZipFiles(request, root+"/zipFiles/"+docId, root);
						System.out.println(rtnDocIds);
						if (rtnDocIds != null) {
							mapper = ResultMapper.generateSuccess();
							mapper.appendResult("id", rtnDocIds);
						} else {
							mapper.appendResult("message", "索引保存失败!");
						}
					}
				} catch (Exception e) {
					e.printStackTrace();
				}					
			}
		}
		response.setCharacterEncoding("UTF-8");
		response.setContentType("text/html; charset=UTF-8");
		response.addHeader("Location", KBProperties.FILEDOMAIN + "?docId="
				+ rtnDocIds);
		try {
			response.sendRedirect(KBProperties.FILEDOMAIN + "?docId="
					+ rtnDocIds);
		} catch (IOException e) {
			e.printStackTrace();
		}

		return mapper.toJson();
	}
	/**
	 * 遍历解压后的文件夹并将所有文件以文件流的方式保存在steamRoot目录下
	 * @Author huangyilun
	 * @param request
	 * @param unZipRoot
	 * @param streamRoot
	 * @return
	 * @throws Exception
	 */
	public String saveUnZipFiles(HttpServletRequest request,String unZipRoot,String streamRoot)throws Exception{
		String docIds = "";
		SysAtt saved = null;
		File fr = new File(unZipRoot);
		File[] fs = fr.listFiles();
		for(int i=0; i<fs.length; i++){
			if(fs[i].isFile()){
				String fileName = fs[i].getName();
				String docId = IDGenerator.getGenerateID();	
				InputStream is = new FileInputStream(fs[i]);				
				String suffix = "";
				if(fileName.lastIndexOf(".")!=-1)
					suffix = fileName.substring(fileName.lastIndexOf(".")+1);
				saved = save2FileStream(request, docId, streamRoot, is, suffix, fileName);
				if (saved != null) {
					docIds+=docId+",";
				}
			}
		}
		if(docIds.length()>0){
			docIds = docIds.substring(0,docIds.length()-1);
		}
		return docIds;
	}
	/**
	 * 将文件保存成文件流，以docId命名存在root目录下
	 * @Author huangyilun
	 * @param request
	 * @param docId
	 * @param root
	 * @param is
	 * @param sysAtt
	 * @return
	 * @throws Exception
	 */
	public SysAtt save2FileStream(HttpServletRequest request,String docId,String root,InputStream is,String suffix,String originalFileName)throws Exception{					
		SysAtt saved = null;
		File destFile = new File(root, docId);
		OutputStream os = new FileOutputStream(destFile);
		byte[] buffer = new byte[KBProperties.INPUTMAX];
		int length = 0;
		while ((length = is.read(buffer)) > 0) {
			os.write(buffer, 0, length);
		}
		is.close();
		os.close();
		SysAtt sysAtt = new SysAtt();
		sysAtt.setDocId(docId);
		sysAtt.setAttPath(root);
		sysAtt.setDocStatus("10");
		sysAtt.setAttSuffix(suffix);
		sysAtt.setDocCreateTime(DateUtils.getNow());
		sysAtt.setDocCreator(UserUtils.getSessionUserBean(request)
				.getSysUser().getDocId());
		sysAtt.setDocSubject(originalFileName);
		sysAtt.setKeyword("FILEUPLOAD");
		saved = iSysAttDao.save(sysAtt);
		return saved;
	}
	/**
	 * @Author Rambo
	 * @Desc：保存对象
	 * @param sysAtt
	 * @param errors
	 * @return TODO
	 * @Version SysAttController.java,v 1.1 2013-11-15 下午4:20:56
	 */
	@RequestMapping(value = "/save", method = RequestMethod.POST)
	@ResponseBody
	public String save(HttpServletRequest request,
			@Valid @ModelAttribute("sysAtt") SysAtt sysAtt, BindingResult errors) {

		if (errors.hasErrors()) {
			mapper = WebUtils.getMapper4Errors(errors);
		} else {
			mapper = iSysAttService.save(sysAtt, request);
		}

		return mapper.toJson();
	}

	/**
	 * @Author Rambo
	 * @Desc：删除对象
	 * @param docId
	 * @param errors
	 * @return TODO
	 * @Version SysAttController.java,v 1.1 2014-9-2 下午3:38:17
	 */
	@RequestMapping(value = "/deleteX", method = RequestMethod.POST)
	@ResponseBody
	public String deleteX(@Valid @ModelAttribute("docId") String docId,
			BindingResult errors) {

		if (errors.hasErrors()) {
			mapper = WebUtils.getMapper4Errors(errors);
		} else {
			mapper = iSysAttService.delete(docId);
		}

		return mapper.toJson();
	}

	/**
	 * @Author Rambo
	 * @Desc：查看对象
	 * @param docId
	 * @param errors
	 * @return TODO
	 * @Version SysAttController.java,v 1.1 2014-9-2 下午3:39:35
	 */
	@RequestMapping(value = "/view", method = RequestMethod.GET)
	@ResponseBody
	public String view(@Valid @ModelAttribute("docId") String docId,
			BindingResult errors) {
		ResultMapper mapperRtn = ResultMapper.generateFailure();
		if (errors.hasErrors()) {
			mapperRtn = WebUtils.getMapper4Errors(errors);
		} else {
			SysAtt sysAtt = iSysAttService.findById(docId);
			mapperRtn = ResultMapper.generateSuccess();
			mapperRtn.appendResult("data", sysAtt);
		}
		return mapperRtn.toJson();
	}

	@RequestMapping(value = "/list", method = RequestMethod.GET)
	@ResponseBody
	public String list(@ModelAttribute("fromDate") String fromDate,
			@ModelAttribute("toDate") String toDate,
			@Valid @ModelAttribute("sysAtt") SysAtt sysAtt,
			@Valid @ModelAttribute("pageBean") PageBean pageBean,
			BindingResult errors) {
		ResultMapper mapperRtn = ResultMapper.generateFailure();
		if (errors.hasErrors()) {
			mapperRtn = WebUtils.getMapper4Errors(errors);
		} else {
			Map conditions = new HashMap();
			conditions.put("fromDate", fromDate);
			conditions.put("toDate", toDate);
			List sysAtts = iSysAttService.getPage(sysAtt, pageBean, conditions);
			int totalCount = iSysAttService.getPageCount(sysAtt, conditions);
			Map map = new HashMap();
			map.put("pageNo", pageBean.getPageNo());
			map.put("pageSize", pageBean.getPageSize());
			map.put("totalCount", totalCount);
			map.put("listData", sysAtts);

			mapperRtn = ResultMapper.generateSuccess();
			mapperRtn.appendResult("data", map);
		}
		return mapperRtn.toJson();
	}

	/**
	 * @Author Rambo
	 * @Desc：状态修改
	 * @param request
	 * @param docId
	 * @param docStatus
	 * @param errors
	 * @return TODO
	 * @Version CateController.java,v 1.1 2014-9-11 上午10:06:04
	 */
	@RequestMapping(value = "/updateStatus", method = RequestMethod.POST)
	@ResponseBody
	public String updateStatus(HttpServletRequest request,
			@Valid @ModelAttribute("docId") String docId,
			@Valid @ModelAttribute("docStatus") String docStatus,
			BindingResult errors) {

		if (errors.hasErrors()) {
			mapper = WebUtils.getMapper4Errors(errors);
		} else {
			if (!StringUtils.isStringEmpty(docId)) {
				SysAtt sysAtt = new SysAtt();

				sysAtt.setDocId(docId);
				sysAtt.setDocStatus(docStatus);
				mapper = iSysAttService.save(sysAtt, request);
			} else {
				mapper = ResultMapper.generateFailure();
				mapper.appendResult("messages", "无法找到该ID!");
			}

		}

		return mapper.toJson();
	}

	/**
	 * @Author Rambo
	 * @Desc：多文件上传
	 * @param files
	 * @param request
	 * @param model
	 * @param sysAtt
	 * @param errors
	 * @return TODO
	 * @Version SysAttController.java,v 1.1 2014-9-12 下午3:55:14
	 */
	@RequestMapping(value = "/uploads", method = RequestMethod.POST)
	@ResponseBody
	public String uploads(
			@RequestParam(value = "files", required = false) MultipartFile[] files,
			HttpServletRequest request, ModelMap model,
			@Valid @ModelAttribute("sysAtt") SysAtt sysAtt, BindingResult errors) {
		mapper = ResultMapper.generateFailure();
		if (files != null && files.length > 0) {
			if (isFileAccess(files)) {
				String root = KBProperties.FILEUPLOAD;
				File dirTemp = new File(root);
				if (!dirTemp.exists()) {
					try {
						dirTemp.mkdirs();
					} catch (Exception ex) {
						try {
							throw new Exception("不能创建目录 :" + root);
						} catch (Exception e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
					}
				}
				for (int i = 0; i < files.length; i++) {
					MultipartFile file = files[i];
					if (!file.isEmpty()) {
						if(file.getContentType().equals("application/x-rar")){

							// 文件传输
							String docId = IDGenerator.getGenerateID();
							InputStream is;
							try {
								is = file.getInputStream();
								File destFile = new File(root, docId);
								OutputStream os = new FileOutputStream(destFile);

								byte[] buffer = new byte[KBProperties.INPUTMAX];
								int length = 0;
								while ((length = is.read(buffer)) > 0) {
									os.write(buffer, 0, length);
								}

								is.close();
								os.close();

								sysAtt.setDocId(docId);
								sysAtt.setAttPath(root);
								sysAtt.setDocStatus("10");
								sysAtt.setAttSuffix(file.getContentType());
								sysAtt.setDocCreateTime(DateUtils.getNow());
								sysAtt.setDocCreator(UserUtils
										.getSessionUserBean(request).getSysUser()
										.getDocId());
								sysAtt.setDocSubject(file.getOriginalFilename()
										.toLowerCase());
								sysAtt.setKeyword("FILEUPLOAD");
								SysAtt saved = iSysAttDao.save(sysAtt);
								if (saved != null) {
									mapper = ResultMapper.generateSuccess();
								} else {
									mapper.appendResult("message", "索引保存失败!");
								}

							} catch (IOException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							}
						}else{

							// 文件传输
							String docId = IDGenerator.getGenerateID();
							InputStream is;
							try {
								is = file.getInputStream();
								File destFile = new File(root, docId);
								OutputStream os = new FileOutputStream(destFile);

								byte[] buffer = new byte[KBProperties.INPUTMAX];
								int length = 0;
								while ((length = is.read(buffer)) > 0) {
									os.write(buffer, 0, length);
								}

								is.close();
								os.close();

								sysAtt.setDocId(docId);
								sysAtt.setAttPath(root);
								sysAtt.setDocStatus("10");
								sysAtt.setAttSuffix(file.getContentType());
								sysAtt.setDocCreateTime(DateUtils.getNow());
								sysAtt.setDocCreator(UserUtils
										.getSessionUserBean(request).getSysUser()
										.getDocId());
								sysAtt.setDocSubject(file.getOriginalFilename()
										.toLowerCase());
								sysAtt.setKeyword("FILEUPLOAD");
								SysAtt saved = iSysAttDao.save(sysAtt);
								if (saved != null) {
									mapper = ResultMapper.generateSuccess();
								} else {
									mapper.appendResult("message", "索引保存失败!");
								}

							} catch (IOException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							}
						}

					}

				}
			}

		}

		return mapper.toJson();
	}

	/**
	 * @Author Rambo
	 * @Desc：单一文件上传
	 * @param file
	 * @param request
	 * @param model
	 * @param sysAtt
	 * @param errors
	 * @return TODO
	 * @Version SysAttController.java,v 1.1 2014-9-12 上午10:47:31
	 */
	@RequestMapping(value = "/upload", method = RequestMethod.POST)
	@ResponseBody
	public String upload(
			@RequestParam(value = "file", required = false) MultipartFile file,
			HttpServletRequest request, ModelMap model,
			@Valid @ModelAttribute("sysAtt") SysAtt sysAtt, BindingResult errors) {
		mapper = ResultMapper.generateFailure();
		if (!file.isEmpty()) {
			MultipartFile[] files = new MultipartFile[1];
			files[0] = file;
			if (isFileAccess(files)) {
				// 文件类型判断
				String root = KBProperties.FILEUPLOAD;
				File dirTemp = new File(root);
				if (!dirTemp.exists()) {
					try {
						dirTemp.mkdirs();
					} catch (Exception ex) {
						try {
							throw new Exception("不能创建目录 :" + root);
						} catch (Exception e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
					}
				}
				// 文件传输
				String docId = IDGenerator.getGenerateID();
				InputStream is;
				try {
					is = file.getInputStream();
					File destFile = new File(root, docId);
					OutputStream os = new FileOutputStream(destFile);

					byte[] buffer = new byte[KBProperties.INPUTMAX];
					int length = 0;
					while ((length = is.read(buffer)) > 0) {
						os.write(buffer, 0, length);
					}

					is.close();
					os.close();

					sysAtt.setDocId(docId);
					sysAtt.setAttPath(root);
					sysAtt.setDocStatus("10");
					sysAtt.setAttSuffix(file.getContentType());
					sysAtt.setDocCreateTime(DateUtils.getNow());
					sysAtt.setDocCreator(UserUtils.getSessionUserBean(request)
							.getSysUser().getDocId());
					sysAtt.setDocSubject(file.getOriginalFilename()
							.toLowerCase());
					sysAtt.setKeyword("FILEUPLOAD");
					SysAtt saved = iSysAttDao.save(sysAtt);
					if (saved != null) {
						mapper = ResultMapper.generateSuccess();
						mapper.appendResult("id", saved.getDocId());
					} else {
						mapper.appendResult("message", "索引保存失败!");
					}

				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

			}
		}
		return mapper.toJson();
	}

	/**
	 * @Author Rambo
	 * @Desc：判断文件是否合法
	 * @param files
	 * @return TODO
	 * @Version SysAttController.java,v 1.1 2014-9-12 下午4:08:12
	 */
	public boolean isFileAccess(MultipartFile[] files) {

		List<String> fileTypes = new ArrayList<String>();
		for (int i = 0; i < files.length; i++) {
			fileTypes.add(files[i].getContentType());
		}
		if (isAllowedType(fileTypes)) {// 类型不符合

		} else {
			return false;
		}
		return true;
	}

	/**
	 * @author Kenshinbo@163.com
	 * @描述：过滤文件类型
	 * @param fileContentType
	 * @return
	 * @version UploadAction.java,v 1.1 Dec 29, 2010 4:18:09 PM KB
	 */
	public boolean isAllowedType(List<String> fileContentType) {
		return true;
		// String fileType = KBProperties.FILETYPE;
		// if (fileContentType != null && fileContentType.size() > 0) {
		// for (int i = 0; i < fileContentType.size(); i++) {
		// if (!fileType.contains(fileContentType.get(i).toString())) {
		// return false;
		// }
		// }
		// return true;
		// }
		// return false;
	}

	/**
	 * @Author Rambo
	 * @Desc：下载文件
	 * @param response
	 * @param docId
	 * @param errors
	 * @return TODO
	 * @Version SysAttController.java,v 1.1 2014-9-15 下午11:16:57
	 */
	@RequestMapping(value = "/download", method = RequestMethod.GET)
	@ResponseBody
	public String download(HttpServletResponse response,
			@Valid @ModelAttribute("docId") String docId, BindingResult errors) {
		ResultMapper mapperRtn = ResultMapper.generateFailure();
		if (errors.hasErrors()) {
			mapperRtn = WebUtils.getMapper4Errors(errors);
		} else {
			SysAtt sysAtt = iSysAttService.findById(docId);
			if (null != sysAtt) {

				InputStream is;
				try {
					is = new FileInputStream(new File(sysAtt.getAttPath() + "/"
							+ sysAtt.getDocId()));
					response.setContentType("octet-stream");
					response.setHeader(
							"Content-Disposition",
							"attachment; filename="
									+ new String(sysAtt.getDocSubject()));
					OutputStream outputStream;
					try {
						outputStream = response.getOutputStream();
						byte[] buffer = new byte[KBProperties.INPUTMAX];
						int i = -1;
						while ((i = is.read(buffer)) != -1) {
							outputStream.write(buffer, 0, i);
						}
						outputStream.flush();
						outputStream.close();
						is.close();
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}

				} catch (FileNotFoundException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

			} else {
				mapper.appendResult("message", "找不到附件!");
				return mapper.toJson();
			}

		}
		return null;
	}

	/**
	 * @Author Rambo
	 * @Desc：根据ids 多文件下载压缩包
	 * @param response
	 * @param docIds
	 * @param errors
	 * @return TODO
	 * @Version SysAttController.java,v 1.1 2014-9-15 下午11:36:21
	 */
	@RequestMapping(value = "/downloads", method = RequestMethod.GET)
	@ResponseBody
	public String downloads(HttpServletResponse response,
			HttpServletRequest request, String[] docIds,
			@Valid @ModelAttribute("sysAtt") SysAtt sysAtt, BindingResult errors) {
		ResultMapper mapperRtn = ResultMapper.generateFailure();
		if (errors.hasErrors()) {
			mapperRtn = WebUtils.getMapper4Errors(errors);
		} else {
			List docList = Arrays.asList(docIds);
			List<SysAtt> sysAttList = iSysAttService.findByIds(docList);
			if (sysAttList.size() > 0) {
				String rootUser = KBProperties.ZIPTEMP
						+ "/["
						+ DateUtils.getNowExt1()
						+ "]"
						+ UserUtils.getSessionUserBean(request).getSysUser()
								.getName();
				String root = KBProperties.ZIPTEMP;
				String downloadId = IDGenerator.getGenerateID();

				try {

					File dirTemp = new File(rootUser);
					if (!dirTemp.exists()) {
						try {
							dirTemp.mkdirs();
						} catch (Exception ex) {
							try {
								throw new Exception("不能创建目录 :" + rootUser);
							} catch (Exception e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							}
						}
					}
					File[] files = new File[sysAttList.size()];
					for (int i = 0; i < sysAttList.size(); i++) {
						FileUtils.copy2(sysAttList.get(i).getAttPath() + "/"
								+ sysAttList.get(i).getDocId(), rootUser + "/"
								+ sysAttList.get(i).getDocSubject());
						files[i] = new File(rootUser + "/"
								+ sysAttList.get(i).getDocSubject());
					}
					ZipUtils.zipFileList(files, root + "/" + downloadId
							+ ".zip", "");
					InputStream is;
					is = new FileInputStream(new File(root + "/" + downloadId
							+ ".zip"));
					response.setContentType("octet-stream");
					response.setHeader("Content-Disposition",
							"attachment; filename="
									+ new String("downloadZip.zip"));
					OutputStream outputStream;
					try {
						outputStream = response.getOutputStream();
						byte[] buffer = new byte[KBProperties.INPUTMAX];
						int i = -1;
						while ((i = is.read(buffer)) != -1) {
							outputStream.write(buffer, 0, i);
						}
						outputStream.flush();
						outputStream.close();
						is.close();
						// 删除zipTemp的临时文件目录（非zip文件）
						FileUtils.deleteDir(new File(rootUser));
					} catch (FileNotFoundException e1) {
						// TODO Auto-generated catch block
						e1.printStackTrace();
					} catch (IOException e1) {
						// TODO Auto-generated catch block
						e1.printStackTrace();
					} catch (Exception e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				} catch (FileNotFoundException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			} else {
				mapper.appendResult("message", "找不到附件列表!");
				return mapper.toJson();
			}

		}
		return null;
	}
}